package com.wmlive.hhvideo.dcijkplayerlib;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;

import com.danikula.videocache.HttpProxyCacheServer;
import com.wmlive.hhvideo.dcijkplayerlib.utils.CacheFileUtil;
import com.wmlive.hhvideo.dcijkplayerlib.utils.L;

import java.io.File;

/**
 * Created by lsq on 6/27/2017.
 * 视频的缓存，支持修改缓存位置
 * SDK6.0以上需要运行时权限{@link Manifest.permission#WRITE_EXTERNAL_STORAGE}
 */

public class Proxy {
    private File cacheFile;
    private HttpProxyCacheServer proxy;

    private static class Holder {
        static final Proxy INSTANCE = new Proxy();
    }

    public static Proxy get() {
        return Holder.INSTANCE;
    }

    /**
     * 获取HttpProxyCacheServer
     *
     * @return
     */
    public HttpProxyCacheServer getProxyServer() {
        return proxy;
    }

    /**
     * 创建视频缓存
     *
     * @param context
     * @param cachePath
     * @return
     */
    private HttpProxyCacheServer newProxy(Context context, File cachePath) {
        if (cachePath == null) {
            //如果cachePath为空，默认使用app的缓存目录
            cachePath = CacheFileUtil.getIndividualCacheDirectory(context);
        }
        L.i("======newProxy");
        HttpProxyCacheServer.Builder builder = new HttpProxyCacheServer.Builder(context);
        if (!cachePath.exists()) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //6.0以上需要运行时权限
                throw new IllegalStateException("you must granted a WRITE_EXTERNAL_STORAGE permission!!!");
            }
            cachePath.mkdirs();
        }
        builder.cacheDirectory(cachePath);
        cacheFile = cachePath;
        proxy = builder.build();
        return proxy;
    }

    /**
     * 获取视频代理
     *
     * @param context
     * @param cache
     * @return
     */
    public HttpProxyCacheServer getProxy(Context context, File cache) {
        if (cache == null || !cache.exists()) {//如果缓存文件为空，则返回默认的proxy
            return newProxy(context.getApplicationContext(), cache);
        }
        if (cacheFile != null) {
            if (!cacheFile.getAbsolutePath().equals(cache.getAbsolutePath())) {//与旧的缓存位置不一致
                if (null != proxy) {
                    proxy.shutdown();
                    L.i("====proxy  shutdown");
                }
            } else {
                if (null == proxy) {
                    return newProxy(context.getApplicationContext(), cache);
                }
                L.i("====返回proxy");
                return proxy;
            }
        }
        return newProxy(context.getApplicationContext(), cache);
    }
}
